package cn.xdf.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author lscl
 * @version 1.0
 * @intro: @RequestParam注解
 */
@Controller
@RequestMapping("/demo02")
public class Demo02Controller_RequestParam {

    //http://localhost:8080/demo02/demo01?id=1&name=guangzhou
    @GetMapping("/demo01")
    public void demo01(Integer id,
                       @RequestParam("name") String cityName, // 将前端传递的name参数与cityName进行绑定(name参数必须传递)
                       HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf8");
        response.getWriter().write("id: " + id + "<hr />");
        response.getWriter().write("cityName: " + cityName + "<hr />");
    }
//400请求参数错误

    @GetMapping("/demo02")
    public void demo02(@RequestParam(required = false) Integer id,                       // id可以不传递
                       @RequestParam(defaultValue = "guangzhou") String cityName,        // cityName参数如果没有传递默认为guangzhou
                       HttpServletResponse response) throws IOException {
//没设置就要传cityName=?才能拿到数据
        response.setContentType("text/html;charset=utf8");
        response.getWriter().write("id: " + id + "<hr />");
        response.getWriter().write("cityName: " + cityName + "<hr />");
    }


    /**
     * map类型
     * @param maps
     * @param response
     * @throws IOException
     */
    @GetMapping("/demo03")
    public void demo03(@RequestParam Map<String, Object> maps,
                       HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf8");
        response.getWriter().write("id: " + maps.get("id") + "<hr />");
        response.getWriter().write("cityName: " + maps.get("cityName") + "<hr />");
    }

    /**
     * List类型
     * @param ids
     * @param response
     * @throws IOException
     */
    @GetMapping("/demo04") //注意参数是ids
    public void demo04(@RequestParam("ids") List<Integer> ids,
                       HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=utf8");
        response.getWriter().write("id: " + ids.toString() + "<hr />");
    }
}
